package me.wz.util.sdbc;

import me.wz.util.sdbc.IIntercept;
import me.wz.util.sdbc.ISdbc;

import java.lang.ref.Reference;
import java.util.concurrent.atomic.AtomicBoolean;

public class Intcpt {

    private static ThreadLocal<IIntercept> once = TLUtil.INTCPT_ONCE;
    private static ThreadLocal<IIntercept> local = TLUtil.INTCPT_LOCAL;

    public static ISdbc once(ISdbc jdbc, IIntercept intcpt) {
        once.set(intcpt);
        return jdbc;
    }
    public static ISdbc local(ISdbc jdbc, IIntercept intcpt) {
        local.set(intcpt);
        return jdbc;
    }

    public static void clear() {
        once.remove();
        local.remove();
    }

    public static String onPrepareStatement(String sql, AtomicBoolean isPrepared) {
        try {
            String ret = sql;

            set(isPrepared, false);

            if( once.get() != null ) {
                ret = once.get().onPrepareStatement(ret);
                set(isPrepared, true);
            }
            if( local.get() != null ) {
                ret = local.get().onPrepareStatement(ret);
                set(isPrepared, true);
            }
            return ret;
        }
        finally {
            once.remove();
        }
    }
    private static void set(AtomicBoolean isPrepared, boolean value) {
        if( isPrepared != null ) {
            isPrepared.set(value);
        }
    }

}
